/*
 * @Author: your name
 * @Date: 2021-08-24 10:54:40
 * @LastEditTime: 2021-09-08 11:29:36
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \bigdate\src\router\index.ts
 */
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { ROOT_ROUTER, PAGE_NOT_FOUND, LOGIN_PAGE, ABOUT_PATH } from './moudule/baseic'  

import { SetLocalStrong, GetLocalStrong, GetAeDecryptLocal, SetAesEncryLocal } from '../ntils/hooks'
import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
// 基础路由
const routerArr = [...ROOT_ROUTER, ...PAGE_NOT_FOUND, ...LOGIN_PAGE, ...ABOUT_PATH]

const asyncRouter: RouteRecordRaw[] = []
// 将初始路由引入

// 权限路由过滤后添加到路由列表中
// asyncRouter 初期写入固定路由 但是需要将有需要的固定路由写在侧边栏
routerArr.forEach((item) => {
    asyncRouter.push(item) 
})

// 创建路由
export const router = createRouter({
    history: createWebHashHistory(),
    routes: asyncRouter as unknown as RouteRecordRaw[],
    strict: true,
    scrollBehavior: () => ({ left: 0, top: 0 }),
})

// 重置路由
export function resetRouter() {
    router.getRoutes().forEach((route) => {
        const { name } = route
        router.removeRoute(name)
    })
}

// 路由首位--检测登录
router.beforeEach((to, from, next) => {
    let role = GetLocalStrong('roles')  
    NProgress.start() // 进度条开始
    if (!role && to.path != '/login') {
        next({ path: '/login' })
    }
    //  在是使用了next()之后下面需要向下放行
     
    next()
})
router.afterEach(() => {
    NProgress.done() // 进度条结束
})
NProgress.configure({ ease: 'linear', speed: 500 })

// 过滤路由

export function routeFilter(arr:Array):Array {
    let tokenRole = GetLocalStrong('roles') 
    // 解密token
    let decryrole = GetAeDecryptLocal(tokenRole)
    decryrole = JSON.parse(decryrole)

    let role = decryrole.value
    let obj = {}
    let len = arr.length
    let z = 0
    let result = []
    for (let n = 0; n < arr.length; n++) {
        if (!obj[arr[n].id]) {
            obj[arr[n].id] = arr[n]    
        } 
    }
    // 这里利用堆栈 定义
    while (z < len) {
        let id = arr[z].id
        let pid = arr[z].preid
        let Atemp = obj[id]
        let Bnode = obj[pid]
        // 只要pid为null 说明就是头部 
        // 其他子节点 通过自己的preid去添加 
        if (pid != null) {
            if (arr[z].roles.includes(role)) {
                Bnode.children.push(arr[z])
            }
        } else if (arr[z].roles.includes(role)) {
            result.push(Atemp)
        } 
        z++
    } 
    return result     
}